﻿using SchoolCommunicationSystem.Models;
using SCS.Business;
using SCS.Common.Models;
using System;
using System.Web.Mvc;
namespace SchoolCommunicationSystem.Controllers
{
    public class PrivateMessageController : Controller
    {
        PrivateMessageService _privateMessageServices = new PrivateMessageService();
        MembershipService _membershipServices = new MembershipService();
        public int ListSize = 1000;

        /// <summary>
        /// Returns the time difference in minutes between two date times
        /// </summary>
        /// <param name="dateone">dateone</param>
        /// <param name="datetwo">datetwo</param>
        /// <returns>TotalMinutes</returns>
        public static double TimeDifferenceInMinutes(DateTime dateone, DateTime datetwo)
        {
            var duration = dateone - datetwo;
            return duration.TotalMinutes;
        }

        /// <summary>
        /// Index
        /// </summary>
        /// <param name="p">int</param>
        /// <returns>View</returns>
        public ActionResult Index(int? p)
        {
            /* if (User.IsInRole(".DisablePrivateMessages == true)
             {
                 TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                 {
                     Message = LocalizationService.GetResourceString("Errors.NoPermission"),
                     MessageType = GenericMessages.error
                 };
                 return RedirectToAction("Index", "Home");
             }*/

            var LoggedOnUser = _membershipServices.GetUser(User.Identity.Name);

            var pageIndex = p ?? 1;
            var pagedMessages = _privateMessageServices.GetPagedReceivedMessagesByUser(pageIndex, ListSize, LoggedOnUser);
            var viewModel = new ListPrivateMessageViewModel
            {
                Messages = pagedMessages,
                PageIndex = pageIndex,
                TotalCount = pagedMessages.TotalCount
            };
            return View(viewModel);
        }

        /// <summary>
        /// SentMessages
        /// </summary>
        /// <param name="p">p</param>
        /// <returns>View</returns>
        public ActionResult SentMessages(int? p)
        {
            var LoggedOnUser = _membershipServices.GetUser(User.Identity.Name);
            var pageIndex = p ?? 1;
            var pagedMessages = _privateMessageServices.GetPagedSentMessagesByUser(pageIndex, ListSize, LoggedOnUser);
            var viewModel = new ListPrivateMessageViewModel
            {
                Messages = pagedMessages
            };
            return View(viewModel);
        }        

        /// <summary>
        /// Pre create message
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>View</returns>
        public ActionResult Create(int? id)
        {
            _membershipServices = _privateMessageServices.GetMembershipService();
            var LoggedOnUser = _membershipServices.GetUser(User.Identity.Name);
            // Check flood control
            var lastMessage = _privateMessageServices.GetLastSentPrivateMessage(LoggedOnUser.userID);

            var viewModel = new CreatePrivateMessageViewModel();
            // See if this is a reply or not
            if (id != null)
            {
                SCS.Common.Models.MembershipUser receiver = _privateMessageServices.GetUserName(id);
                viewModel.UserToUsername = receiver.userName;
                viewModel.Subject = string.Empty;
                viewModel.PreviousMessage = string.Empty;
            }
            return View(viewModel);
        }

        /// <summary>
        /// AutoComplete
        /// </summary>
        /// <param name="term">string</param>
        /// <returns>Json(filteredItems)</returns>
        public ActionResult AutoComplete(string term)
        {
        /*    var allUser = _membershipServices.GetAllUser();
            List<string> list = new List<string>();

            foreach (var item in allUser)
            {
                list.Add(item.userName);
            }

            var filteredItems = list.Where(
                item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
                );*/
            var filteredItems = _membershipServices.AutoComplete(term);
            return Json(filteredItems, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// create message
        /// </summary>
        /// <param name="createPrivateMessageViewModel">CreatePrivateMessageViewModel</param>
        /// <returns>View</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CreatePrivateMessageViewModel createPrivateMessageViewModel)
        {
            _membershipServices = _privateMessageServices.GetMembershipService();
            var LoggedOnUser = _membershipServices.GetUser(User.Identity.Name);
            if (ModelState.IsValid)
            {
                var userTo = createPrivateMessageViewModel.UserToUsername;

                // first check they are not trying to message themself!
                if (userTo.ToLower() != LoggedOnUser.userName.ToLower())
                {
                    // Map the view model to message
                    var privateMessage = new PrivateMessage
                    {
                        UserFrom = LoggedOnUser,
                        subject = createPrivateMessageViewModel.Subject,
                        message = createPrivateMessageViewModel.Message,
                    };
                    // now get the user its being sent to
                    var memberTo = _membershipServices.GetUser(userTo);

                    // check the member
                    if (memberTo != null)
                    {
                        privateMessage.UserTo = memberTo;
                        _privateMessageServices.Add(privateMessage);

                        return RedirectToAction("SentMessages");
                    }
                    else
                    {
                        // Error send back to user
                        ModelState.AddModelError(string.Empty, "Người nhận không tồn tại");
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Không thể gửi cho chính mình");
                }
            }
            return View(createPrivateMessageViewModel);
        }

        /// <summary>
        /// View message
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>View</returns>
        public ActionResult View(int id)
        {
            var LoggedOnUser = _membershipServices.GetUser(User.Identity.Name);
            var message = _privateMessageServices.Get(id);

            if (message.UserTo.userName == User.Identity.Name | message.UserFrom.userName == User.Identity.Name)//LoggedOnUser)
            {
                //Mark as read if this is the receiver of the message
                if (message.UserTo.userName == User.Identity.Name)
                {
                    // Update message as read
                    message.isRead = true;
                    _privateMessageServices.Save(message);
                }

                return View(new ViewPrivateMessageViewModel { Message = message });
            }

            return RedirectToAction("Index", "Home");
        }

        /// <summary>
        /// Delete a message
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>View</returns>
        public ActionResult Delete(int id)
        {
            var LoggedOnUser = _membershipServices.GetUser(User.Identity.Name);
            var message = _privateMessageServices.Get(id);

            if (message.UserTo.userName == User.Identity.Name | message.UserFrom.userName == User.Identity.Name)//LoggedOnUser)
            {
                if (message.UserTo.userName == User.Identity.Name)
                {
                    _privateMessageServices.DeleteMessage(message, false);
                }
                else if (message.UserFrom.userName == User.Identity.Name)
                {
                    _privateMessageServices.DeleteMessage(message, true);
                }
                else
                {
                    throw new Exception("No Permison");
                }
            }

            return RedirectToAction("Index", "PrivateMessage");
        }
    }
    /*
    internal ActionResult ErrorToInbox(string errorMessage)
    {
        // Use temp data as its a redirect
        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
        {
            Message = errorMessage,
            MessageType = GenericMessages.error
        };
        // Not allowed in here so
        return RedirectToAction("Index", "PrivateMessage");
    }
     * */
}
